package api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import domain.Product;
import service.ProductService;
import utils.GetRequestJsonUtils;
import utils.Response;
import utils.ResponseCode;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

public class GetBooksServlet extends HttpServlet {
    //该请求可以携带参数：分类查询，还可以携带分页参数，也可以什么都不携带，就是查询所有书目
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        JSONObject paramsObject =GetRequestJsonUtils.getRequestJsonObject(req);
        // 参数格式{category:"",pageSize:10,pageIndex:3},获取所有书目{}
     if (paramsObject.containsKey("category")) {
         String category = paramsObject.getString("category");
     }
     if (paramsObject.containsKey("pageSize")){
         int pageSize=paramsObject.getInteger("pageSize");
     }
     if (paramsObject.containsKey("pageIndex")) {
         int pageIndex = paramsObject.getInteger("pageIndex");
     }
        ProductService service=new ProductService();
        Response build=null;
     if (paramsObject==null){
         try {
             List<Product> books = service.getAllProducts();
             build= Response.build(ResponseCode.SUCCESS,books);
         }catch (SQLException e){
             e.printStackTrace();
             build=Response.build(ResponseCode.ERROR_DB);
         }
     }else {
         build=Response.build(ResponseCode.ERROR);
     }
        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().write(JSON.toJSON(build).toString());
    }
}
